import json
from typing import List, Union, Optional, Dict, Tuple

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ses.v20201002 import ses_client, models

from .config import CONF


def send_email(
    Destination: Union[str, List[str]],
    Subject: str,
    TemplateData: Union[dict, str],
    FromEmailAddress: Optional[str] = None,
    ReplyToAddresses: Optional[str] = None,
    TemplateID: Optional[int] = None,
    Unsubscribe: Optional[str] = None,
    TriggerType: Optional[int] = None,
    secretId: Optional[str] = None,
    secretKey: Optional[str] = None,
    defaultConf: Optional[Dict[str, str]] = CONF['tencentcloud_ses']['verification_code']
) -> Tuple[int, str]:
    """
    发送模板邮件

    Args:
        Destination (Union[str, List[str]]): 收件人(列表)
        Subject (str): 邮件主题
        TemplateData (Union[dict, str]): json或json字符串
        FromEmailAddress (Optional[str], optional): 发件人地址. Defaults to None.
        ReplyToAddresses (Optional[str], optional): 邮件的“回复”电子邮件地址. Defaults to None.
        TemplateID (Optional[int], optional): 模板ID. Defaults to None.
        Unsubscribe (Optional[str], optional): 退订选项 "1": 加入退订链接 "0": 不加入退订链接. Defaults to None.
        TriggerType (Optional[int], optional): 邮件触发类型 0:非触发类，默认类型，营销类邮件、非即时类邮件等选择此类型 1:触发类，验证码等即时发送类邮件，若邮件超过一定大小，系统会自动选择非触发类型通道. Defaults to None.
        secretId (Optional[str], optional): SDK secretId. Defaults to None.
        secretKey (Optional[str], optional): SDK secretKey. Defaults to None.
        defaultConf (Optional[Dict[str, str]], optional): 默认配置, 配置项为None时会从该字典中获取. Defaults to CONF['tencentcloud_ses']['verification_code'].

    Returns:
        Tuple[int, str]: err_code, err_info
    """
    if not isinstance(Destination, list):
        Destination = [Destination]
    if isinstance(TemplateData, dict):
        template_data = json.dumps(TemplateData)
    else:
        template_data = TemplateData

    if secretId is None:
        secretId = defaultConf['secretId']
    if secretKey is None:
        secretKey = defaultConf['secretKey']
    if FromEmailAddress is None:
        FromEmailAddress = defaultConf['FromEmailAddress']
    if ReplyToAddresses is None:
        ReplyToAddresses = defaultConf['ReplyToAddresses']
    if TemplateID is None:
        TemplateID = defaultConf['TemplateID']
    if Unsubscribe is None:
        Unsubscribe = defaultConf['Unsubscribe']
    if TriggerType is None:
        TriggerType = defaultConf['TriggerType']

    err_code = 0
    err_info = ''
    try:
        cred = credential.Credential(secretId, secretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ses.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = ses_client.SesClient(cred, "ap-hongkong", clientProfile)

        req = models.SendEmailRequest()
        params = {
            "FromEmailAddress": FromEmailAddress,
            "ReplyToAddresses": ReplyToAddresses,
            "Destination": Destination,
            "Template": {
                "TemplateID": TemplateID,
                "TemplateData": template_data
            },
            "Subject": Subject,
            "Unsubscribe": Unsubscribe,
            "TriggerType": TriggerType
        }
        req.from_json_string(json.dumps(params))

        resp = client.SendEmail(req)
        js = json.loads(resp.to_json_string())
        # print(json.dumps(js, indent=2, ensure_ascii=False))
        """
        正常发送Response:
        {
            "Response": {  # 实际没有"Response"这一层
                "MessageId": "qcloudses-30-1255871247-date-20220511172929-KVZuJnokfCkJ1",
                "RequestId": "da1d10cd-4813-4d51-b8ed-0e12aae9cdd7"
            }
        }
        错误发送Response:
        {
            "Response": {  # 实际没有"Response"这一层
                "Error": {
                    "Code": "InvalidParameterValue.EmailContentIsWrong",
                    "Message": "参数取值错误。邮件内容错误，请检查TEXT/HTML base64是否正确。"
                },
                "MessageId": "",
                "RequestId": "ee58f40f-f042-48cf-8196-66098248acea"
            }
        }
        """
        if "Error" not in js:
            err_code = 0
        else:
            err_code = 1
            err_info = js["Error"]["Message"]

    except TencentCloudSDKException as err:
        err_code = 1
        err_info = "[TencentCloudSDKException] " + str(err)
    return err_code, err_info
